﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;

namespace MopsesPetShop
{
    /// <summary>
    /// Сводное описание для ImageHandler
    /// </summary>
    public class ImageHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "Image/Png";
            var id = int.Parse(context.Request["id"]);
            var sizeH = -1;
            var sizeW = -1;
            if(!string.IsNullOrEmpty(context.Request["sizeH"]))
                sizeH = int.Parse(context.Request["sizeH"]);
            if (!string.IsNullOrEmpty(context.Request["sizeW"]))
                sizeW = int.Parse(context.Request["sizeW"]);
            var dc = new DataClasses1DataContext();
            var ms = new MemoryStream(dc.Pictures.Where(pic => pic.pk == id).First().picture.ToArray());
            var img = Image.FromStream(ms);
            if (!string.IsNullOrEmpty(context.Request["sizeH"]) && !string.IsNullOrEmpty(context.Request["sizeW"]))
                img = img.GetThumbnailImage(sizeW, sizeH, null, IntPtr.Zero);
            var stream = new MemoryStream();
            img.Save(stream,ImageFormat.Png);
            var buffer = stream.GetBuffer();
            context.Response.OutputStream.Write(buffer,0,buffer.Length);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}